import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';

import { getWithList } from '../api';
import WithdrowItem from '../models/WithdrowItem';
import WithdrowList, { WithdrowQuery } from '../models/WithdrowList';

const useWithList = () => {
  const params = ref(new WithdrowQuery());
  const pageState = ref({
    finished: false,
    refreshing: false,
    error: false,
  });
  const state = ref<ListState<WithdrowItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const fetchData = async () => {
    try {
      if (pageState.value.refreshing) {
        state.value.data = [];
        pageState.value.refreshing = false;
      }
      pageState.value.error = false;
      state.value.loading = true;
      const { data } = await getWithList(params.value);
      const resultData = deserialize(data, WithdrowList);
      state.value.data.push(...resultData.items);
      state.value.total = resultData.total;
    } catch {
      pageState.value.error = true;
    } finally {
      state.value.loading = false;
      if (state.value.data.length >= state.value.total) {
        pageState.value.finished = true;
      } else {
        params.value.pageNum += 1;
      }
    }
  };

  const refresh = async () => {
    pageState.value.finished = false;
    params.value.pageNum = 1;
    fetchData();
  };

  return {
    params,
    state,
    pageState,
    fetchData,
    refresh,
  };
};

export default useWithList;
